package com.ruoyi.app.controller;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.ruoyi.common.utils.ApiResult;
import com.ruoyi.ums.entity.Member;
import com.ruoyi.ums.entity.MemberCoupon;
import com.ruoyi.ums.service.IMemberCouponService;
import com.ruoyi.ums.service.IMemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Api(tags = "获取微信用户信息")
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IMemberCouponService memberCouponService;

    @ApiOperation("获取用户accessToken")
    @RequestMapping(value = "/getAccessToken", method = RequestMethod.GET)
    public ApiResult<WxMaJscode2SessionResult> getAccessToken(@RequestParam("code") String code) {
        WxMaJscode2SessionResult result = memberService.registerUser(code);
        return ApiResult.success(result);
    }

    @ApiOperation("获取用户信息")
    @RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
    public ApiResult<WxMaUserInfo> getUserInfo(@RequestParam("sessionKey") String sessionKey,
                                               @RequestParam("encryptedData") String encryptedData,
                                               @RequestParam("ivStr") String ivStr) {

        WxMaUserInfo info = memberService.getUserInfo(sessionKey, encryptedData, ivStr);
        return ApiResult.success(info);
    }

    @ApiOperation("获取用户优惠券")
    @RequestMapping(value = "/getUserCoupon", method = RequestMethod.GET)
    public ApiResult<List<MemberCoupon>> getUserCoupon() {
        Member member = this.getMember();
        return ApiResult.success(memberCouponService.selectCoupons(member.getId()));
    }
}
